<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" 
	xmlns:v="urn:schemas-microsoft-com:vml">
<head>
	<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
	<title>Geo-DB: KML Library</title>
	
	<!-- Google Map #includes -->

	<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAT6O-9c7l12-hQp5xSbyDyxQy2yniISssRVCUeDY5K11434tp4BS0Z2M7hHdI0WTeOu13R-wrM3u2qw"
	type="text/javascript"></script>
	<script type='text/javascript' src='http://www.google.com/jsapi'></script>
	<script src="/js/util.js" type="text/javascript"></script>

	<script type="text/javascript"> 
 
	var map;
	var geoXml;
	var KML_URL;
	var xmlDoc;
	var response_timer;
	var str='123-222';
	var GAE_FetchUrl_MaxTime = 10;
	var GAE_FetchUrl_Timer = GAE_FetchUrl_MaxTime;
	//var PathxmlDoc;
	var ScrollPathList = [];
	var ScrollPathList_idx = -1;
	var UniqueID = 0;
	var PathEnd_Placemarks;// = new Array(2)
	var PathEndMarks = new Array(2);
	var PathEnd_underlineMarks = new Array(2);
	var Nearby_Landmarks = new Array(2);
	var Landmarks_Available = new Array(2);

	google.load('visualization', '1', {'packages':['annotatedtimeline']});

	function initialize() {
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("map_canvas")); 
			map.setCenter(new GLatLng(41.875696,-87.624207), 11); 
			
			map.addControl(new GMapTypeControl());
			map.addControl(new GLargeMapControl());

			document.getElementById("debug_text").innerHTML = "Initialized";
			document.getElementById("id_debug_str").value="go";
			
			NearbyLandmarks_Init();
		}
	}
	function queryKMLUrl(){
		KMLinfo_Request(document.getElementById('tmp_kml_input').value,-1);
	}
	function KMLinfo_Request(KML_URL,List_idx){
		d = new Date();
		response_timer = d.getTime();

		document.getElementById("debug_text").innerHTML = "before geoxml-kml POST sent";
		downloadUrl("/getKMLinfo", "POST", "content=" + encodeURI(KML_URL), function(responseText){onKMLinfo_Returned(responseText,List_idx)});
		document.getElementById("debug_text").innerHTML = "geoxml-kml POST sent";
	}

	function onKMLinfo_Returned(responseText,List_idx) {
		d = new Date();
		document.getElementById("srv_resp_time").value = (d.getTime()-response_timer)/1000;
		
		xml_indx=responseText.indexOf("<GeoInfo>");
		xml_string=responseText.substring(xml_indx, responseText.length);
		document.getElementById("id_debug_str").value = xml_string;
		xmlDoc = geoDB_DOMParser(xml_string);
		//docu=parser.parseFromString(xml_string,"text/xml");
		Debug_str = xmlDoc.getElementsByTagName("DebugInfo")[0].childNodes[0].nodeValue;
		document.getElementById("debug_text").innerHTML = Debug_str;
		KMLurl = xmlDoc.getElementsByTagName("KMLurl")[0].childNodes[0].nodeValue;

		if (Debug_str.indexOf('Success:') != -1){
			// KML info has been received successfully
			GAE_FetchUrl_Timer = GAE_FetchUrl_MaxTime;
			if (geoXml!=null){map.removeOverlay(geoXml);}
			NearbyLandmarks_Reset();
			geoXml = new GGeoXml(KMLurl );
			
			map.addOverlay(geoXml);
			map.setCenter(geoXml.getDefaultCenter(), 11);
			geoXml.gotoDefaultViewport(map);
			PathList = ParsePathItems(xmlDoc);//Return An Array with single item 
			PathEnd_Placemarks = Parse_PathEnd_Placemarks(xmlDoc);
			ScrollPathList_addItems(PathList,List_idx);
			Display_PathInfo(PathList[0]);
			
			AutoRetrive_NextPath(List_idx+1);
			if($('#AutoFetchTypes').val()!=1){
				drawChart_TimeLine("velocity");
				drawChart_TimeLine("height");
				document.getElementById("debug_text").innerHTML = document.getElementById("debug_text").innerHTML + "Auto Retrieve Next: "+document.getElementById('AutoFetchTypes').value;
			}
		}
		else{
			if (Debug_str.indexOf('Error: Download Error:') != -1){
				// encounter error on getting KML info
				if (GAE_FetchUrl_Timer > 0){
					// Retry getting KML info
					GAE_FetchUrl_Timer = GAE_FetchUrl_Timer-1;
					KMLinfo_Request(KMLurl,List_idx);
					Debug_str = Debug_str + 'Retry Time = ' + (GAE_FetchUrl_MaxTime-GAE_FetchUrl_Timer);
					document.getElementById("debug_text").innerHTML = Debug_str;
				}
				else{
					// Give up getting KML info
					GAE_FetchUrl_Timer = GAE_FetchUrl_MaxTime;
					Debug_str = Debug_str + 'Failed';
					document.getElementById("debug_text").innerHTML = Debug_str;
					
					AutoRetrive_NextPath(List_idx+1);
				}
			}
			else{
				if (Debug_str.indexOf('Error: Invalid URL:') != -1){
					// Give up getting KML info
					GAE_FetchUrl_Timer = GAE_FetchUrl_MaxTime;
					Debug_str = Debug_str + 'Failed';
					document.getElementById("debug_text").innerHTML = Debug_str;
					
					AutoRetrive_NextPath(List_idx+1);
				}
			}
		}
	}
	function AutoRetrive_NextPath(NextPath_idx){
		if($('#AutoFetchTypes').val()==1){
			//Auto Retrieve
			if ((NextPath_idx < ScrollPathList.length)&&(NextPath_idx>=0)){
				document.getElementById("debug_text").innerHTML = "Auto Retrieve Next: id= "+NextPath_idx;
				ScrollPathList_ManualClick(NextPath_idx);
			}
		}
	}
	function ScrollPathList_ManualClick(NextPath_idx){
		var api = $("div.scrollable").scrollable();
		api.click(NextPath_idx);
		ScrollPathList_onClick(NextPath_idx);
	}
	function ScrollPathList_onClick(NextPath_idx){
		PathItem = ScrollPathList[NextPath_idx];
		KMLinfo_Request(PathItem.KMLurl,NextPath_idx);
		document.getElementById("select_id").value=String(NextPath_idx);
		ScrollPathList_idx = NextPath_idx;
	}
	function string2datetime(str){
		datetime_str = str.split(' ');
		date_str = datetime_str[0].split('-');
		year=Number(date_str[0]);
		month=Number(date_str[1]);
		day=Number(date_str[2]);

		time_str = datetime_str[1].split(':');
		hour=Number(time_str[0]);
		minute=Number(time_str[1]);
		second=Number(time_str[2]);

		return new Date(year,month-1,day,hour,minute,second)
	}
	function drawChart_TimeLine(Prop_Str) {
		var data = new google.visualization.DataTable();
		data.addColumn('datetime', 'Time');
		data.addColumn('number', Prop_Str);
		data.addColumn('string', 'title1');
		data.addColumn('string', 'text1');
		
		datetimes = xmlDoc.getElementsByTagName("datetime");
		data.addRows(datetimes.length);
		for(idx = 0;idx < datetimes.length;idx = idx +1){
			data.setValue(idx, 0, string2datetime(datetimes[idx].childNodes[0].nodeValue));
		}
		
		velocitys = xmlDoc.getElementsByTagName(Prop_Str);
		for(idx = 0;idx < velocitys.length;idx = idx +1){
			data.setValue(idx, 1, Number(velocitys [idx].childNodes[0].nodeValue));
		}

		var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('chart_div_'+Prop_Str));
		chart.draw(data, {displayAnnotations: true});
		
		document.getElementById("placemark_num").value = datetimes.length;
	}
	function KMLinfoSet_Request(){
		Source = document.getElementById("Source").value;
		ScrollPathList[ScrollPathList_idx].Source = Source;
		Destination = document.getElementById("Destination").value;//
		ScrollPathList[ScrollPathList_idx].Destination = Destination;
		Description = document.getElementById("PathDescription").value;//Description
		ScrollPathList[ScrollPathList_idx].Description = Description;
		StartDatetime = ScrollPathList[ScrollPathList_idx].StartDatetime;
		EndDatetime = ScrollPathList[ScrollPathList_idx].EndDatetime;
		
		content_str = "<GeoInfo><StartDatetime>"+StartDatetime+"</StartDatetime><EndDatetime>"+EndDatetime +"</EndDatetime>";
		
		for (var End_idx=0;End_idx<2;End_idx=End_idx+1){
			if (End_idx==0){
				End_Name = "Source";
			}
			else{
				End_Name = "Destination";
			}
			Placemark_Name = document.getElementById(End_Name).value;
			if (PathEndMarks[End_idx]!=-1){
				//debug
				document.getElementById("debug_text").innerHTML = "KMLinfoSet_Request:End_idx"+End_idx+",PathEndMarks:"+PathEndMarks[End_idx];
				Landmark = Nearby_Landmarks[End_idx][PathEndMarks[End_idx]].getLatLng();
				content_str = content_str + "<" + End_Name + "><Name>"+Placemark_Name+"</Name><lat>" + Landmark.lat() +"</lat><lng> " + Landmark.lng() + "</lng></" + End_Name + ">";
			}
		}
		content_str = content_str + "<Path>";
		if (Description!="None"){
			content_str = content_str + "<Description>" + Description + "</Description>";
		}
		content_str = content_str + "</Path></GeoInfo>";
		document.getElementById("id_debug_str").value = 'local:'+content_str;
		
		downloadUrl("/setKMLinfo", "POST", "content=" + encodeURI(content_str), onKMLinfoSetConfirmReturned);//
	}
	function onKMLinfoSetConfirmReturned(responseText){
		document.getElementById("debug_text").innerHTML = responseText;
	}
	function NearbyLandmarks_Request(End_idx){
		//Nearby_Landmarks
		if (Landmarks_Available[End_idx] == false){
			lat = PathEnd_Placemarks[End_idx].lat();
			lng = PathEnd_Placemarks[End_idx].lng();
			GLatLngBounds = map.getBounds();
			rad = GLatLngBounds.toSpan().lng()/2;
			document.getElementById("debug_text").innerHTML = "Nearby Landmarks Request: Sent: End_idx = "+End_idx;
			downloadUrl("/getLANDMARKinfo?lat="+lat+"&lng="+lng+"&rad="+rad+"&End_idx="+End_idx, "GET", "content=", function(responseText) {onNearbyLandmarks_Returned(responseText,End_idx);});
		}
		else{
			document.getElementById("debug_text").innerHTML = "Nearby Landmarks Request: Already Exists: End_idx = "+End_idx;
			
			NearbyLandmarks_Show(End_idx);
			Other_End = 1 - End_idx;
			if (Nearby_Landmarks[Other_End]!=null){
				if (Nearby_Landmarks[Other_End].length){
					NearbyLandmarks_Hide(Other_End);
				}
			}
		}
	}
	function onNearbyLandmarks_Returned(responseText,End_idx){
		document.getElementById("debug_text").innerHTML = "Nearby Landmarks Response Received:"+End_idx;
		document.getElementById("id_debug_str").value = 'received:'+responseText;
		Landmarks_Available[End_idx] = true;
		xmlDoc = geoDB_DOMParser(responseText);
		
		xmlDoc_Placemarks = xmlDoc.getElementsByTagName("Placemark");
		if (End_idx==0){
			End_Name = ScrollPathList[ScrollPathList_idx].Source;
		}
		else{
			End_Name = ScrollPathList[ScrollPathList_idx].Destination;
		}
		Landmark_num = xmlDoc_Placemarks.length;
		//new Array(Landmark_num);
		for (idx=0;idx<Landmark_num;idx=idx+1){
			xmlDoc_names = xmlDoc_Placemarks[idx].getElementsByTagName("name")[0];
			name = xmlDoc_names.childNodes[0].nodeValue;
			xmlDoc_coordinates = xmlDoc_Placemarks[idx].getElementsByTagName("coordinates")[0];
			coordinates = xmlDoc_coordinates.childNodes[0].nodeValue.split(",");
			lng = Number(coordinates[0]);
			lat = Number(coordinates[1]);
			xmlDoc_descriptions = xmlDoc_Placemarks[idx].getElementsByTagName("description")[0];
			description = xmlDoc_descriptions.childNodes[0].nodeValue;
			distance = Number(xmlDoc_Placemarks[idx].getElementsByTagName("distance")[0].childNodes[0].nodeValue);
			
			Landmark = NearbyLandmarks_Add(End_idx, new GLatLng(lat, lng), name, description,distance);
			
			if (End_Name!='None'){
				if (End_Name == name){
					NearbyLandmarks_SetEnd(End_idx, Landmark.id);
				}
			}
			else{
				if (PathEndMarks[End_idx]==-1){
					if (idx==0){
						//PathEndMarks[End_idx]=Landmark.id;
						NearbyLandmarks_SetEnd(End_idx, Landmark.id);
					}
				}
			}
		}
		
		NearbyLandmarks_Show(End_idx);
		Other_End = 1 - End_idx;
		if (Nearby_Landmarks[Other_End]!=null){
			if (Nearby_Landmarks[Other_End].length){
				NearbyLandmarks_Hide(Other_End);
			}
		}
	}
	function NearbyLandmarks_creatNew(End_idx){
		position_init = map.getCenter();//geoXml.getVertex(0);//
		Landmark = NearbyLandmarks_Add(End_idx, position_init, "No Name", "<![CDATA[No Description]]>");
		//PathEndMarks[End_idx]=Landmark.id;
		NearbyLandmarks_SetEnd(End_idx, Landmark.id);
	}
	function NearbyLandmarks_Init(){
		for (var End_idx=0;End_idx<2;End_idx=End_idx+1){
			PathEndMarks[End_idx]=-1;
			Nearby_Landmarks[End_idx] = new Array();
			Landmarks_Available[End_idx] = false;
		}
	}
	function Landmark_GenerateInfoHtml(Landmark){
		Start_Tag = "<![CDATA[";
		inner_start = Landmark.description.indexOf(Start_Tag)+Start_Tag.length;
		inner_end = Landmark.description.lastIndexOf("]]>");
		gLatLng = Landmark.getLatLng();
		InfoHtml = "<h2>"+Landmark.getTitle()+"</h2><p>"+Landmark.description.substring(inner_start,inner_end)+"</p><p>Coordinate=("+gLatLng.lng()+","+gLatLng.lat()+")</p><p>distance="+Landmark.distance+"</p>";
		document.getElementById("id_debug_str").value = 'genrated:'+InfoHtml;
		return InfoHtml;
	}
	function NearbyLandmarks_SetEnd(End_idx, idx){
		if (PathEndMarks[End_idx]==-1){
			PathEndMarks[End_idx]=idx;
			var gIcon = new GIcon(G_DEFAULT_ICON);
			gIcon.image = "/css/images/underline"+End_idx+"0.png";
			gIcon.iconAnchor = new GPoint(8,-1);
			gIcon.iconSize = new GSize(19, 11);
			gIcon.shadow = null;
			gLatLng = Nearby_Landmarks[End_idx][idx].getLatLng();
			gLatLng_offset = new GLatLng(gLatLng.lat(),gLatLng.lng());//+0.0000001
			PathEnd_underlineMarks[End_idx] = new GMarker(gLatLng_offset, {icon: gIcon});
			map.addOverlay(PathEnd_underlineMarks[End_idx]);
		}
		else{
			PathEndMarks[End_idx]=idx;
			gLatLng = Nearby_Landmarks[End_idx][idx].getLatLng();
			gLatLng_offset = new GLatLng(gLatLng.lat(),gLatLng.lng());//+0.0000001
			PathEnd_underlineMarks[End_idx].setLatLng(gLatLng_offset);
		}
		if (End_idx==0){End_name = "Source";}	else{End_name = "Destination";}
		document.getElementById(End_name).value = Nearby_Landmarks[End_idx][idx].getTitle();//(overlay).getTitle();
	}
	function NearbyLandmarks_Add(End_idx, gLatLng, name, description,distance){
		var Landmark = new GMarker(gLatLng,{ title: name, draggable: true});
		Landmark.description = description;
		Landmark.distance = distance;
		
		Landmark.id = Nearby_Landmarks[End_idx].length;
		Landmark.ClickEventListener = GEvent.addListener(Landmark, "click", function(overlay, latlng) {
			
			//document.getElementById("id_debug_str").value= 'Path Info: ' + End_name + ': Set';
			//gMarker = new GMarker(latlng);
			//PathEndMarks[End_idx]=Landmark.id;
			NearbyLandmarks_SetEnd(End_idx, Landmark.id);
			Landmark.openInfoWindowHtml(Landmark_GenerateInfoHtml(Landmark));
		});
		Landmark.DragstartEventListener = GEvent.addListener(Landmark, "dragstart", function() {
			Landmark.closeInfoWindow();
		});
		Landmark.DragendEventListener = GEvent.addListener(Landmark, "dragend", function() {
			Landmark.openInfoWindowHtml(Landmark_GenerateInfoHtml(Landmark));
			NearbyLandmarks_SetEnd(End_idx, Landmark.id);
		});
		//Nearby_Landmarks[End_idx][idx] = Landmark;
		Nearby_Landmarks[End_idx].push(Landmark);
		map.addOverlay(Landmark);
		return Landmark;
	}
	function NearbyLandmarks_Show(End_idx){
		Landmark_num = Nearby_Landmarks[End_idx].length;
		for (var idx=0;idx<Landmark_num;idx=idx+1){
			//var Landmark = Nearby_Landmarks[End_idx][idx];
			//map.addOverlay(Nearby_Landmarks[End_idx][idx]);
			Nearby_Landmarks[End_idx][idx].show();
		}
	}
	function NearbyLandmarks_Hide(End_idx){
		Landmark_num = Nearby_Landmarks[End_idx].length;
		for (idx=0;idx<Landmark_num;idx=idx+1){
			//map.removeOverlay(Nearby_Landmarks[End_idx][idx]);
			Nearby_Landmarks[End_idx][idx].hide(); 
		}
	}
	function NearbyLandmarks_Reset(){
		for (var End_idx=0;End_idx<2;End_idx=End_idx+1){
			if (PathEndMarks[End_idx]!=-1){
				map.removeOverlay(PathEnd_underlineMarks[End_idx]);
				PathEnd_underlineMarks[End_idx]=null;
				PathEndMarks[End_idx]=-1;
			}
			
			Landmarks_Available[End_idx] = false;
			while (Nearby_Landmarks[End_idx].length){
				Landmark = Nearby_Landmarks[End_idx].pop();
				GEvent.removeListener(Landmark.ClickEventListener);
				GEvent.removeListener(Landmark.DragstartEventListener);
				GEvent.removeListener(Landmark.DragendEventListener);
				map.removeOverlay(Landmark);
			}
			
		}
	}
	</script>

	<!-- jQuery UI #includes -->

	<link type="text/css" href="css/ui.core.css" rel="stylesheet" />
	<link type="text/css" href="css/ui.theme.css" rel="stylesheet" />
	<script type='text/javascript' src='/js/util.js'></script>
	<!-- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> -->
	<script src="offline/jquery.min.js"></script>
	<script type="text/javascript" src="js/effects.core.js"></script>
	<script type="text/javascript" src="js/effects.drop.js"></script>
	<link type="text/css" href="css/demos.css" rel="stylesheet" />
	<style type="text/css">
		.toggler { width: 500px; height: 20px; }
		#button { padding: .5em 1em; text-decoration: none; }
		#effect { width: 740px; height: 170px; padding: 0.4em; position: relative; }
		#effect h3 { margin: 0; padding: 0.4em; text-align: center; }
		.ui-effects-transfer { border: 2px dotted gray; }
	</style>

	<!-- jQuery UI Toggle -->
	<script type="text/javascript">
	$(function() {
		//run the currently selected effect
		function runEffect(){
			//get effect type from
			var selectedEffect = $('#effectTypes').val();
			
			//most effect types need no options passed by default
			var options = {};
			//check if it's scale, transfer, or size - they need options explicitly set
			//if(selectedEffect == 'scale'){  options = {percent: 0}; }
			//else if(selectedEffect == 'size'){ options = { to: {width: 200,height: 60} }; }
			options = {direction: 'up'}
			//run the effect
			$("#effect").toggle(selectedEffect,options,500);
		};
		
		//set effect from select menu value
		$("#button").click(function() {
			runEffect();
			return false;
		});
	});
	</script>

	<!-- jQuery UI plugins: Scrollable includes -->

	<script src="js/jquery.mousewheel.js"></script>
	<script src="js/jquery.scrollable-1.0.2.min.js"></script>
	<link rel="stylesheet" type="text/css" href="css/scrollable-minimal.css" />
	<link rel="stylesheet" type="text/css" href="css/scrollable-navig.css" />

	<!-- jQuery UI plugins: Scrollable -->

	<script>
	//var response_timer;
	//var GAE_FetchUrl_MaxTime = 5;
	//var GAE_FetchUrl_Timer = GAE_FetchUrl_MaxTime;
	
	// execute your scripts when DOM is ready. this is a good habit
	$(function() {
		var scrollable_api = $("div.scrollable").scrollable();
		//	select items under the second scrollable and do something when they are clicked
		//$("div.scrollable div.items div").click(function() {
		//	document.getElementById("select_id").innerHTML=this.innerHTML;//scrollable_api.getIndex(); //4;
		//});
	});
	function KMLCollectionAdd(AddFilterOn_val){
		if (AddFilterOn_val){
			isAddFilterOn = 'On';
		}
		else{
			isAddFilterOn = 'Off';
		}
		
		Path_Col_URL = document.getElementById("Path_URL_input").value;
		KMLCollectionAdd_Request(Path_Col_URL,isAddFilterOn);
	}
	function KMLCollectionUpdate() {
		Path_Col_URL = "";//document.getElementById("Path_URL_input").innerHTML;
		KMLCollectionAdd_Request(Path_Col_URL,'Off');
	}
	function KMLCollectionAdd_Request(Path_Col_URL,isAddFilterOn){
		d = new Date();
		response_timer = d.getTime();
		
		document.getElementById("debug_text").innerHTML = "before geoxml-kml POST sent";
		//downloadUrl("/getPATHinfo", "POST", "content="+encodeURI(Path_Col_URL), onKMLCollectionAdd_Returned);
		downloadUrl("/getPATHinfo?Path_Col_URL="+Path_Col_URL+"&Filter="+isAddFilterOn, "GET", "content=", onKMLCollectionAdd_Returned);
		document.getElementById("debug_text").innerHTML = "geoxml-kml POST sent";
	}
	function onKMLCollectionAdd_Returned(responseText){
		//document.getElementById("id_debug_str").value=responseText;
		onKMLCollection_Returned(responseText);
	}
	
	function onKMLCollection_Returned(responseText) {
		//google.setOnLoadCallback(drawChart);
		document.getElementById("debug_text").innerHTML = "Path info received";
		d = new Date();
		document.getElementById("srv_resp_time").value = (d.getTime()-response_timer)/1000;
		document.getElementById("id_debug_str").value = responseText;
		
		xml_indx=responseText.indexOf("<PathInfo>");
		xml_string=responseText.substring(xml_indx, responseText.length);
		document.getElementById("id_debug_str").value = xml_string;
		xmlDoc = geoDB_DOMParser(xml_string);
		
		Debug_str = xmlDoc.getElementsByTagName("DebugInfo")[0].childNodes[0].nodeValue;
		document.getElementById("debug_text").innerHTML = Debug_str;
		//KMLurl = xmlDoc.getElementsByTagName("KMLurl")[0].childNodes[0].nodeValue;

		if (Debug_str.indexOf('Success:') != -1){
			//PathxmlDoc = xmlDoc;
			GAE_FetchUrl_Timer = GAE_FetchUrl_MaxTime;
			PathList = ParsePathItems(xmlDoc);
			document.getElementById("debug_text").innerHTML = document.getElementById("debug_text").innerHTML + '->Path Num:'+PathList.length;
			ScrollPathList_addItems(PathList,-1);
		}
		else{
			if (GAE_FetchUrl_Timer > 0){
				GAE_FetchUrl_Timer = GAE_FetchUrl_Timer-1;
				KMLinfo_Request(KML_URL,List_idx);//Bug
				Debug_str = Debug_str + 'Retry Time = ' + (GAE_FetchUrl_MaxTime-GAE_FetchUrl_Timer);
				document.getElementById("debug_text").innerHTML = Debug_str;
			}
			else{
				GAE_FetchUrl_Timer = GAE_FetchUrl_MaxTime;
				Debug_str = Debug_str + 'Failed';
				document.getElementById("debug_text").innerHTML = Debug_str;
			}
		}
    }
	function geoDB_DOMParser(xml_string){
		try //Internet Explorer
		{
			xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.async="false";
			xmlDoc.loadXML(xml_string);
		} catch(e) {
			try //Firefox, Mozilla, Opera, etc.
			{
				parser=new DOMParser();
				xmlDoc=parser.parseFromString(xml_string,"text/xml");
			}
			catch(e) { alert(e.message); return; }
		}
		return xmlDoc;
	}
	function ParsePathItems(xmlDoc) {
		PathList = [];
		Paths = xmlDoc.getElementsByTagName("Path");
		StartDatetimes = xmlDoc.getElementsByTagName("StartDatetime");
		
		for(idx = 0;idx < Paths.length;idx = idx +1){
			// append new item using jQuery's append() method
			Path = Paths[idx];
			PathItem = new Object();
			PathItem.KMLurl = Path.getElementsByTagName("KMLurl")[0].childNodes[0].nodeValue;
			PathItem.StartDatetime = Path.getElementsByTagName("StartDatetime")[0].childNodes[0].nodeValue;
			PathItem.EndDatetime = Path.getElementsByTagName("EndDatetime")[0].childNodes[0].nodeValue;
			PathItem.Source = Path.getElementsByTagName("Source")[0].childNodes[0].nodeValue;//
			PathItem.Destination = Path.getElementsByTagName("Destination")[0].childNodes[0].nodeValue;
			PathItem.Distance = Path.getElementsByTagName("Distance")[0].childNodes[0].nodeValue;//Duration
			PathItem.Duration = Path.getElementsByTagName("Duration")[0].childNodes[0].nodeValue;//
			PathItem.MaxVelocity = Path.getElementsByTagName("MaxVelocity")[0].childNodes[0].nodeValue;//
			PathItem.Description = Path.getElementsByTagName("Description")[0].childNodes[0].nodeValue;
			PathList.push(PathItem);
		}
		return PathList;
	}
	function Parse_PathEnd_Placemarks(xmlDoc){
		var Placemarks = new Array(2);
		lats = xmlDoc.getElementsByTagName("lat");
		for (End_idx=0;End_idx<2;End_idx=End_idx+1){
			if (End_idx==1){PathEnd_idx=lats.length-1;}
			else {PathEnd_idx=0;}
			lat = Number(lats[PathEnd_idx].childNodes[0].nodeValue);
			lngs = xmlDoc.getElementsByTagName("lng");
			lng = Number(lngs[PathEnd_idx].childNodes[0].nodeValue);
			Placemarks[End_idx]=new GLatLng(lat,lng);
		}
		return Placemarks;
	}
	function ScrollPathList_addItems(PathList,List_idx){
		// get handle to scrollable api
		var api = $("div.scrollable").scrollable();
		
		document.getElementById("debug_text").innerHTML = document.getElementById("debug_text").innerHTML + 'len:'+ScrollPathList.length;
		
		for(idx = 0;idx < PathList.length;idx = idx +1){
			if (PathList[idx].StartDatetime != 'None'){
				for(idx2 = 0;idx2 < ScrollPathList.length;idx2 = idx2 +1){
					if (PathList[idx].StartDatetime == ScrollPathList[idx2].StartDatetime){
						ScrollPathList_UpdateItem(api,PathList[idx],idx2);
						break;
					}
				}
			}
			if (List_idx>=0){
				ScrollPathList_UpdateItem(api,PathList[idx],List_idx);
			}
			else{
				ScrollPathList_addItem(api,PathList[idx]);
			}
		}
		
		$("div.scrollable div.items div").click(function() {
			ScrollItem_onClick(this.id);
		});
		// rebuild scrollable and move to the end to see what happened	
		api.reload();
		api.click(ScrollPathList_idx);
	}
	function ScrollPathList_addItem(api,PathItem){
		api.getItemWrap().append('<div id=i'+ UniqueID + ' >' + UniqueID + '<br>' + PathItem.StartDatetime+'<br>' + 'Distance:'+ PathItem.Distance + '</div>');
		PathItem.id=UniqueID;
		ScrollPathList.push(PathItem);
		UniqueID = UniqueID+1;
		document.getElementById("debug_text").innerHTML = document.getElementById("debug_text").innerHTML + 'v';
	}
	function ScrollPathList_UpdateItem(api,PathItem,idx2){
		Old_UniqueID = ScrollPathList[idx2].id;
		api.getItems().filter(':eq('+ idx2 +')').replaceWith('<div id=i'+ Old_UniqueID + ' >' + Old_UniqueID+'<br>'+PathItem.StartDatetime+'<br>' + 'Distance:'+ PathItem.Distance + '</div>');
		PathItem.id = Old_UniqueID;
		ScrollPathList[idx2] = PathItem;
		document.getElementById("debug_text").innerHTML = document.getElementById("debug_text").innerHTML + 'x';
	}
	function ScrollPathList_DeleteItem(api,idx){
		ScrollPathList_tail = ScrollPathList.splice(idx+1);
		ScrollPathList.pop();
		ScrollPathList=ScrollPathList.concat(ScrollPathList_tail);
		api.getItems().filter(":eq("+idx+")").remove();
		
		if (idx>=ScrollPathList.length){
			idx = idx-1;
		}
		return idx;
	}
	function ScrollPathList_Clear(){
		var api = $("div.scrollable").scrollable();
		if (ScrollPathList_idx<0){
			if (ScrollPathList.length>0){
				ScrollPathList_idx=0;
			}
		}
		while (ScrollPathList_idx>=0){
			ScrollPathList_idx = ScrollPathList_DeleteItem(api,ScrollPathList_idx);
		}
		document.getElementById("select_id").value=String(ScrollPathList_idx);
		api.reload();
	}
	function ScrollItem_onClick(id_str){
		id = Number(id_str.substring(1, id_str.length));
		for (idx=0;idx<ScrollPathList.length;idx=idx+1){
			if(ScrollPathList[idx].id==id){
				break;
			}
		}
		ScrollPathList_onClick(idx);
	}
	
	function Display_PathInfo(PathItem){
		document.getElementById("tmp_kml_input").value = PathItem.KMLurl;
		document.getElementById("StartDatetime").value = PathItem.StartDatetime;
		document.getElementById("EndDatetime").value = PathItem.EndDatetime;
		document.getElementById("Source").value = PathItem.Source;
		document.getElementById("Destination").value = PathItem.Destination;
		document.getElementById("Distance").value = PathItem.Distance;
		document.getElementById("Duration").value = PathItem.Duration;//
		document.getElementById("MaxVelocity").value = PathItem.MaxVelocity;
		document.getElementById("PathDescription").value = PathItem.Description;
	}
	function KMLinfoDelete_Request(){
		PathItem = ScrollPathList[ScrollPathList_idx];
		downloadUrl("/delKMLinfo?StartDatetime="+PathItem.StartDatetime+"&EndDatetime="+PathItem.EndDatetime, "GET", "content=", onKMLinfoDelete_Returned);
	}
	function onKMLinfoDelete_Returned(responseText){
		if (responseText.indexOf('Success:') != -1){
			//Deletion Success
			GAE_FetchUrl_Timer = GAE_FetchUrl_MaxTime;
			var api = $("div.scrollable").scrollable();
			
			ScrollPathList_idx = ScrollPathList_DeleteItem(api,ScrollPathList_idx);
			
			$("div.scrollable div.items div").click(function() {
				ScrollItem_onClick(this.id);
			});
			document.getElementById("select_id").value=String(ScrollPathList_idx);
			api.reload();
			
			api.click(ScrollPathList_idx);
			
			document.getElementById("debug_text").innerHTML = responseText;
			if($('#AutoFetchTypes').val()==1){
				//Auto Retrieve
				if (ScrollPathList.length){
					deleteKMLinfo();
				}
				else{
					document.getElementById("debug_text").innerHTML = 'all deleted';
				}
			}
		}
		else{
			Debug_str = responseText;
			// encounter error on getting KML info
			if (GAE_FetchUrl_Timer > 0){
				// Give up getting KML info
				GAE_FetchUrl_Timer = GAE_FetchUrl_Timer-1;
				deleteKMLinfo();
				Debug_str = Debug_str + 'Retry Time = ' + (GAE_FetchUrl_MaxTime-GAE_FetchUrl_Timer);
				document.getElementById("debug_text").innerHTML = Debug_str;
			}
			else{
				// Retry getting KML info
				GAE_FetchUrl_Timer = GAE_FetchUrl_MaxTime;
				Debug_str = Debug_str + 'Failed';
				document.getElementById("debug_text").innerHTML = Debug_str;
				
				if($('#AutoFetchTypes').val()==1){
					//Auto Retrieve
					ScrollPathList_idx = ScrollPathList_idx+1;
					
					var api = $("div.scrollable").scrollable();
					api.click(ScrollPathList_idx);
					
					deleteKMLinfo();
				}
			}
		}
	}
	
	function mytest(){
	}
	
	</script>

</head>

<body onload="initialize()">
<div class="demo">
	<!-- header bar -->

	<div align="right">
	{% if user %}
		Logged in as {{ user.nickname }} - 
		<a href="/edituser/{{ user.email }}">Edit My Profile</a> -
		<a href="{{log_in_out_url}}">Log out</a>
	{% else %}
		<a href="{{log_in_out_url}}">Log in</a>
	{% endif %}
	| <a href="http://appengine.google.com/dashboard?&app_id=geo-db">Site Management</a>
	</div>

	<!-- header toggle -->

	<div align="left" style="position:absolute; top:3px;">
	<select id="AutoFetchTypes">
		<option value=0>Disable</option>
		<option value=1>Auto</option>
	</select>
	
	<select name="effects" id="effectTypes">
		<option value="drop">Drop</option>
	</select>
	<input type="button" value="test" onClick="mytest();"></input>
	<a href="#" id="button" class="ui-state-default ui-corner-all">Hide/Show</a>
	</div>
	<div class="toggler" id="toggler" style="position:absolute; left:300px; top:3px; z-Index:1;">click on me to show/hide toggle panel
		<div id="effect" class="ui-widget-content ui-corner-all">
			<h3 class="ui-widget-header ui-corner-all">NEW KML Collection URL:
                                <input name="content" type="text" id="Path_URL_input" size="30" value="http://groups.google.com/group/xconn/web/kmls2008"></input>
								<input type="button" value="Add" onClick="KMLCollectionAdd(1);"></input>
                                <input type="button" value="All+Add" onClick="KMLCollectionAdd(0);"></input>
								<input type="button" value="Update" onClick="KMLCollectionUpdate();"></input>
								<input type="button" value="Clear local list" onClick="ScrollPathList_Clear();"></input>
            </h3>
			<!-- prev link -->
			<a class="prev"></a>

			<!-- root element for scrollable -->
			<div class="scrollable">
				<!-- root element for the items -->
				<div class="items">
					
				</div>
			</div>

			<!-- next link -->
			<a class="next"></a>
			<!-- navigator -->
			<div class="navi"></div>
		</div><!-- End effect -->
	</div><!-- End toggler -->
	<!-- let rest of the page float normally <br clear="all" />-->
</div><!-- End demo -->

	<table>
		<tr>
			<!-- Google Map Canvas -->
			<th>
				<div id="map_canvas" style="width: 800px; height: 480px; float:left; border: 1px solid black;"></div></div>
			</th>
			<!-- KML info -->
			<th>
	KML file URL:
	<input name="content" type="text" id="tmp_kml_input" size="30" value="http://www.fileden.com/files/2009/2/3/2304551/KMLs2008/WirelessGene_M-241_Start_20080301-190946_Finish_20080301-191002.kml"></input><br />
	<input type="button" value="Load KML" onClick="queryKMLUrl()"></input><br />
	Placemark Number: <input name="content2" type="text" id="placemark_num" size="20" value="0"></input><br />
	Server Response Time (Sec): <input name="content3" type="text" id="srv_resp_time" size="20" value="0"></input><br />
	Seleted ID: <input type="text" id="select_id" size="20" value="0"></input><br />
	Start Date Time: <input type="text" id="StartDatetime" size="20" value="0"></input><br />
	End Date time: <input type="text" id="EndDatetime" size="20" value="0"></input><br />
	Source: <input type="text" id="Source" size="20" value="0" onfocus="NearbyLandmarks_Request(0)"></input><input type="button" value="New" onClick="NearbyLandmarks_creatNew(0);"></input><br />
	Destination: <input type="text" id="Destination" size="20" value="0" onfocus="NearbyLandmarks_Request(1)"></input></input><input type="button" value="New" onClick="NearbyLandmarks_creatNew(1);"></input><br />
	Distance: <input type="text" id="Distance" size="20" value="0"></input><br />
	Duration: <input type="text" id="Duration" size="20" value="0"></input><br />
	MaxVelocity: <input type="text" id="MaxVelocity" size="20" value="0"></input><br />
	Description:<textarea id="PathDescription" rows="3" cols="20" value="is null"></textarea><br />
	<input type="button" value="Delete KML" onClick="KMLinfoDelete_Request();"></input><input type="button" value="Update KML" onClick="KMLinfoSet_Request();"></input>
	<div id="debug_text" style="padding:10px;background-color:white;width:100%;height:85%; overflow:auto;"></div>
			</th>
		</tr>
	</table>
	<br clear="all"/>
	<!-- Debug Info -->

	
	<div id='chart_div_velocity' style='width: 700px; height: 240px;'></div>
	<div id='chart_div_height' style='width: 700px; height: 240px;'></div>
	<textarea name="debug_str" id="id_debug_str" rows="10" cols="80" value="is null"></textarea>
</body>
</html>
